﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TBR.Common;
using TBR.Entities;
using TBR.Entities.Message;

namespace TBR.Repositories
{
    public class MessageRepository
    {
        #region constructor
        public MessageRepository()
        {
            this.webhelper = new WebHelper();
            this.htmlhelper = new HtmlHelper();
            this.Messages = new List<Message>();
        }
        #endregion

        #region events
        public delegate void RequestEventHandler(object source, RequestEventArgs args);
        public class RequestEventArgs : EventArgs
        {
            public IList<Message> Messages;
        }
        #endregion

        #region GetMessagesCompleted
        public event RequestEventHandler GetMessagesCompleted;
        public void OnGetMessagesCompleted()
        {
            if (GetMessagesCompleted != null)
            {
                RequestEventArgs args = new RequestEventArgs();
                args.Messages = Messages;
                GetMessagesCompleted(this, args);
            }
        }

        private void webHelper_GetMessagesCompleted(object sender, TBR.Common.WebHelper.RequestEventArgs args)
        {
            if (args.HtmlCode.IndexOf("Переписка") > 0)
            {
                webhelper.RequestCompleted -= webHelper_GetMessagesCompleted;
                List<string> strMessages = htmlhelper.GetDivCollections(args.HtmlCode, "Ваши диалоги", "pages", "</div></div>", "<div>").ToList();
                Messages = ExtractMessages(strMessages);
                //OnGetMessagesCompleted();
                IList<Message> messagesOnCurrentPage = ExtractMessages(strMessages);
                bool isPagesEnded = Messages.Any(u =>
                {
                    foreach (var message in messagesOnCurrentPage)
                        if (message.Date == u.Date && message.TextMessage == u.TextMessage && message.Sender.Id == u.Sender.Id)
                            return true;
                    return false;
                });

                if (isPagesEnded)
                {
                    OnGetMessagesCompleted();
                }
                else
                {
                    foreach (var message in messagesOnCurrentPage)
                        Messages.Add(message);
                    currentPage++;
                    GetMessages(currentPage);
                }
            }
            else
            {
                Messages = null;
                OnGetMessagesCompleted();
            }
        }
        #endregion

        #region properties
        private WebHelper webhelper { get; set; }
        private HtmlHelper htmlhelper { get; set; }
        private IList<Message> Messages { get; set; }
        private bool IsSended { get; set; }
        private int currentPage = 1;
        #endregion

        #region public methods
        public void GetMessages(int page)
        {
            webhelper.RequestCompleted += webHelper_GetMessagesCompleted;
            string sid = CookieHelper.GetPropertyCookieByKey("sid");
            webhelper.GetHtmlCode(new Uri(String.Format("http://tabor.ru/newmessages.php?p={0}&sid={1}", page, sid)), WebHelper.Method.Get);
        }
        #endregion

        #region private methods
        private IList<Message> ExtractMessages(IList<string> strList)
        {
            var messages = new List<Message>();
            foreach (var div in strList)
            {
                var senderName = GetSenderName(div);
                var id = GetSenderId(div);
                var sex = GetSenderSex(div);
                var imgUrl = GetImageUrl(div);
                var age = GetAge(div);
                var actionDate = GetActionDate(div);
                messages.Add(new Message
                {
                    Date = actionDate,
                    TextMessage = GetTextMessage(div),
                    Sender = new User(id, senderName, imgUrl, age, String.Empty, sex, actionDate)
                });
            }
            return messages;
        }

        private string GetSenderName(string text)
        {
            text = text.Substring(0, text.IndexOf("</a>"));
            return text.Remove(0, text.LastIndexOf(">") + 1);
        }

        private string GetSenderId(string text)
        {
            text = text.Remove(0, text.IndexOf("id=") + 3);
            return text.Substring(0, text.IndexOf("&amp;"));
        }

        private ESex GetSenderSex(string text)
        {
            return text.IndexOf("boy.png") != -1 ? ESex.Male : ESex.Female;
        }

        private string GetImageUrl(string text)
        {
            string begin = "><img src=\"";
            text = text.Remove(0, text.IndexOf(begin) + begin.Length);
            text = text.Remove(0, text.IndexOf(begin) + begin.Length);
            return text.Remove(text.IndexOf("\""));
        }

        private int GetAge(string text)
        {
            string begin = "</a>, ";
            text = text.Remove(0, text.IndexOf(begin) + begin.Length);
            return int.Parse(text.Remove(2));
        }

        private string GetLocation(string text)
        {
            string begin = "/></a></div><div>";
            text = text.Remove(0, text.IndexOf(begin) + begin.Length + 1);
            return text.Remove(text.IndexOf("<"));
        }

        private string GetActionDate(string text)
        {
            int startSpanIndex = text.IndexOf("<span");
            int endSpanIndex = text.IndexOf("span>");
            if (startSpanIndex != -1 && endSpanIndex != -1 && startSpanIndex < endSpanIndex)
            {
                string span = text.Substring(startSpanIndex, endSpanIndex - startSpanIndex);
                int startIndex = span.IndexOf(">") + 1;
                int endIndex = span.LastIndexOf("<");
                return span.Substring(startIndex, endIndex - startIndex);
            }
            else return String.Empty;
        }

        private string GetTextMessage(string text)
        {
            return text.Substring(text.IndexOf("<br/>") + 5, text.LastIndexOf("<br/>") - text.IndexOf("<br/>") - 5);
        }
        #endregion
    }
}
